const RATE = 7; // 1 USD = 7 CNY

function handleConversion() {
    const input = document.getElementById('amountInput').value.trim();
    const resultDiv = document.getElementById('result');
    const errorDiv = document.getElementById('error');
    
    // 清空之前的显示
    resultDiv.textContent = '';
    errorDiv.textContent = '';
    
    // 验证输入格式
    const match = input.match(/^(\d+\.?\d*)\s+(USD|CNY)$/i);
    if (!match) {
        showError('格式错误！请输入类似 "100 USD" 或 "500 CNY" 的格式');
        return;
    }
    
    const amount = parseFloat(match[1]);
    const currency = match[2].toUpperCase();
    
    // 验证金额有效性
    if (amount <= 0) {
        showError('金额必须为正数');
        return;
    }
    
    // 执行兑换计算
    let result;
    if (currency === 'USD') {
        result = `${amount} USD = ${(amount * RATE).toFixed(2)} CNY`;
    } else {
        result = `${amount} CNY = ${(amount / RATE).toFixed(2)} USD`;
    }
    
    // 显示结果
    resultDiv.textContent = result;
    document.getElementById('amountInput').value = ''; // 清空输入框
}

function showError(message) {
    const errorDiv = document.getElementById('error');
    errorDiv.textContent = message;
    // 3秒后自动清除错误信息
    setTimeout(() => {
        errorDiv.textContent = '';
    }, 3000);
}
